//
//  PickerListViewController.m
//  League
//
//  Created by 崔璨 on 2018/1/25.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "PickerListViewController.h"
#import "ProdileModel.h"
#import "ProfileManager.h"

#define kHeadViewH 80

#define kCellH 50

#define kTitleLabSize 14
@interface PickerListViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger saveSelectIndex;
     NSBundle *bundle;
}
@property(strong , nonatomic)UIView *headView;
@property(strong , nonatomic)UITableView *tableV;
@property(strong , nonatomic)NSMutableArray *dataSource;
@property (strong, nonatomic) ProfileManager *manager;

@property(strong , nonatomic)NSMutableArray *saveSelectedIndexList;
@property(strong , nonatomic)UIButton *cancelBtn;
@end

@implementation PickerListViewController
-(void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kPickerNotifoStr object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%d",self.isRadio);
    NSLog(@"%@",@(self.index));
    self.dataSource = [NSMutableArray array];
    saveSelectIndex = -1;
    self.saveSelectedIndexList = [NSMutableArray array];
    [InternationalControl initUserLanguage];//初始化应用语言
    
    bundle = [InternationalControl bundle];
    self.manager = [ProfileManager shareManager];
    [self HeadView];
    [self TableView];
    [self getProfile];
    // Do any additional setup after loading the view.
}
-(void)HeadView
{
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kHeadViewH)];
//    self.headView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.headView];
    
    self.cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.headView.width/5, self.headView.height/2)];
    self.cancelBtn.center = CGPointMake(self.headView.width - self.cancelBtn.width/2, self.headView.height - self.cancelBtn.height/2);
    [self.cancelBtn setTitle:[bundle localizedStringForKey:@"done" value:nil table:@"hello"] forState:UIControlStateNormal];
    [self.cancelBtn addTarget:self action:@selector(cancelBtn:) forControlEvents:UIControlEventTouchDown];
    [self.cancelBtn setTitleColor:kAppColor forState:UIControlStateNormal];
    [self.headView addSubview:self.cancelBtn];
}
-(void)cancelBtn:(UIButton *)btn
{
    if (saveSelectIndex == -1) {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    ProdileModel *model = self.dataSource[saveSelectIndex];
    NSDictionary *dict = @{@"list":self.saveSelectedIndexList, @"index":@(self.index),@"selectIndex":@(saveSelectIndex), @"data":model};
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:kPickerNotifoStr object:nil userInfo:dict];
    }];
}
-(void)TableView
{
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, self.headView.height, self.view.width, self.view.height-self.headView.height)];//指定位置大小
    self.tableV.backgroundColor = [UIColor clearColor];
    [self.tableV setDelegate:self];//指定委托
    [self.tableV setDataSource:self];//指定数据委托
    self.tableV.estimatedRowHeight = 0;
    self.tableV.estimatedSectionHeaderHeight = 0;
    self.tableV.estimatedSectionFooterHeight = 0;
    self.tableV.layer.masksToBounds = YES;
    self.tableV.layer.cornerRadius = 10;
    self.tableV.tableFooterView = [UIView new];
    [self.view addSubview:self.tableV];//加载tableview
    
}

- (void)getProfile {
    NSDictionary *parameters;
    if (self.type == PreferEducation) {
        parameters = @{
                         @"parentid":@"0",
                         @"typename":@"PreferEducation"
                         };
    }
    if (self.type == Religion) {
        parameters = @{
                         @"parentid":@"0",
                         @"typename":@"Religion"
                         };
    }
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kGetDictionary];
    [DataContrller PostRequestUrl:urlStr Param:parameters requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            for (NSDictionary *city in backDic[@"obj"]) {
                ProdileModel *model = [[ProdileModel alloc] initWithDictionary:city error:nil];
                if (model != nil) {
                    if (self.isProfile == YES) {
                        for (NSString *string in self.manager.religionsArray) {
                            if ([string integerValue] == [model._id integerValue]) {
                                model.isSelect = YES;
                            }
                        }
                    } else {
                        if (self.type == PreferEducation) {
                            for (NSString *string in self.manager.preferEducationsArray) {
                                if ([string integerValue] == [model._id integerValue]) {
                                    model.isSelect = YES;
                                }
                            }
                        } else {
                            for (NSString *string in self.manager.preferReligionsArray) {
                                if ([string integerValue] == [model._id integerValue]) {
                                    model.isSelect = YES;
                                }
                            }
                        }
                    }
                    [self.dataSource addObject:model];
                }
            }
            [self.tableV reloadData];
        } else {
        
        }
    } requestFail:^(NSString *backErrorStr) {
        
        NSLog(@"backErrorStr:%@",backErrorStr);
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell"];
    //    if (!cell) {
    //        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"TableViewCell"];
    //
    //    }
    static NSString *CellIdentifier = @"TableViewCell";
    // 通过indexPath创建cell实例 每一个cell都是单独的
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.width = tableView.width;
        cell.height = kCellH;
    }
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, cell.width - 40, cell.height)];
    titleLab.font=[UIFont fontWithName:kFontName size:kTitleLabSize];
    [cell addSubview:titleLab];
    
    ProdileModel *model = self.dataSource[indexPath.row];
    
    NSString *lan = [InternationalControl userLanguage];
    if([lan isEqualToString:@"en"]){//判断当前的语言，进行改变
        titleLab.text = model.categoryDesc;
    } else {
        titleLab.text = model.categoryName;
    }
    UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, cell.height*0.6, cell.height*0.6)];
    selectBtn.center = CGPointMake(cell.width-selectBtn.width/2-20, cell.height/2);
//    selectBtn.backgroundColor = [UIColor yellowColor];
    selectBtn.tag = indexPath.row;
    selectBtn.userInteractionEnabled = NO;
    [cell addSubview:selectBtn];

    
    if (model.isSelect == YES) {
        [selectBtn setImage:[UIImage imageNamed:@"BtnSelected"] forState:UIControlStateNormal];
    } else {
        [selectBtn setImage:[UIImage imageNamed:@"BtnNotSelected"] forState:UIControlStateNormal];
    }
    
    if (self.isProfile == NO && self.type == PreferEducation) {
        //look for Education 单选
        for (NSString *string in self.manager.preferEducationsArray) {
            if ([string isEqualToString:model._id]) {
                [selectBtn setImage:[UIImage imageNamed:@"BtnSelected"] forState:UIControlStateNormal];
                self.manager.preferEducation = model.categoryName;
            } else {
                [selectBtn setImage:[UIImage imageNamed:@"BtnNotSelected"] forState:UIControlStateNormal];
            }
        }
    }
    /*
    if (self.isRadio == YES) {
        if (saveSelectIndex == indexPath.row) {
            [selectBtn setImage:[UIImage imageNamed:@"BtnSelected"] forState:UIControlStateNormal];
        }
        else{
            [selectBtn setImage:[UIImage imageNamed:@"BtnNotSelected"] forState:UIControlStateNormal];
        }
    }
    
    else{
        
        if ([self.saveSelectedIndexList containsObject: @(indexPath.row)]) {
            [selectBtn setImage:[UIImage imageNamed:@"BtnSelected"] forState:UIControlStateNormal];
        }
        else{
            [selectBtn setImage:[UIImage imageNamed:@"BtnNotSelected"] forState:UIControlStateNormal];
        }
    }
    */

    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"row:%@ - section:%@",@(indexPath.row) , @(indexPath.section));
    NSInteger i = indexPath.row;
    [self saveSelectIndexRow:i];
}
-(void)saveSelectIndexRow:(NSInteger )indexRow
{
    if (self.isRadio == YES) {
        
        saveSelectIndex = indexRow;
        
    }
    else
    {
        BOOL isbool = [self.saveSelectedIndexList containsObject: @(indexRow)];
        if (isbool == YES) {
            NSLog(@"有");
            [self.saveSelectedIndexList removeObject:@(indexRow)];
        }
        else
        {
            NSLog(@"没有");
            [self.saveSelectedIndexList addObject:@(indexRow)];
        }
    }
    ProdileModel *model = self.dataSource[indexRow];
    model.isSelect = !model.isSelect;
    if (self.isProfile == YES) {
        if (self.type == Religion) {
            if (model.isSelect == YES) {
                [self.manager.religionsArray addObject:model._id];
            } else {
                [self.manager.religionsArray removeObject:model._id];
            }
        }
    } else {
        if (self.type == Religion) {
            if (model.isSelect == YES) {
                [self.manager.preferReligionsArray addObject:model._id];
            } else {
                [self.manager.preferReligionsArray removeObject:model._id];
            }
        } else {
            if (model.isSelect == YES) {
                if (self.manager.preferEducationsArray.count == 0) {
                    [self.manager.preferEducationsArray addObject:model._id];
                } else {
                    [self.manager.preferEducationsArray replaceObjectAtIndex:0 withObject:model._id];
                }
            } else {
                [self.manager.preferEducationsArray replaceObjectAtIndex:0 withObject:model._id];
            }
        }
    }
    [self.dataSource replaceObjectAtIndex:indexRow withObject:model];
    [self.tableV reloadData];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return kCellH;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
